package com.smartrobot.smartrobot.activity;

import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;

import com.easemob.chat.ImageMessageBody;
import com.github.siyamed.shapeimageview.CircularImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.smartrobot.smartrobot.Common.Common;
import com.smartrobot.smartrobot.R;
import com.smartrobot.smartrobot.circle.commonData;
import com.smartrobot.smartrobot.circle.searchAndAddFriend;
import com.smartrobot.smartrobot.logToSdCard.LogToSd;
import com.smartrobot.smartrobot.pojo.getFriendListPojo;
import com.smartrobot.smartrobot.util.HttpUtil;
import com.smartrobot.smartrobot.util.ImageLoaderApi;
import com.smartrobot.smartrobot.util.PeopleRegisterMsg;
import com.smartrobot.smartrobot.util.User;
import com.smartrobot.smartrobot.view.ToastCustom;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

//import java.util.logging.Handler;

public class SocialAddActivity extends Activity{
    private EditText user_account;
    private Button user_add;
    private CircularImageView user_head;
    private ImageView add_friend_back;
    private TextView user_name,user_sign,user_role,scan_friend_from_qr,search;
    private Handler handle = new searchAndFriendHandle();
    private getFriendListPojo userMsg = new getFriendListPojo();
    private RelativeLayout userMsgLayout;
    private ProgressBar add_progressBar;
    public final static int  RETURN_FROM_QR_ACTIVITY = 10;



    Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null){
            throw new NullPointerException();
        }
        this.setContentView(R.layout.page_social_circle_add_friend);

        initActivity();//初始化activity



        /*发起添加好友的请求*/
        user_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addFriendRequest();
            }
        });

        /*从二维码中添加好友*/
        scan_friend_from_qr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent1 = new Intent();
                intent1.setClass(getApplicationContext(),MipcaActivityCapture.class);
                SocialAddActivity.this.startActivityForResult(intent1, RETURN_FROM_QR_ACTIVITY);

            }
        });

        add_friend_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                SocialAddActivity.this.finish();
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm= (InputMethodManager) getSystemService(SocialAddActivity.this.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(SocialAddActivity.this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                searchFriend();

            }
        });

        user_account.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {

                if(id == 0){
                    searchFriend();
                }

                return false;
            }
        });

    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RETURN_FROM_QR_ACTIVITY: {
                if (resultCode ==RESULT_OK) {//返回成功
                    Bundle bundle = data.getExtras(); //获取返回来的字符串
                    String result = bundle.getString("result").toString();

                    try{
                        JSONObject json_result = new JSONObject(result);
                        String userId = json_result.optString("ID");

                        if(userId==null||userId.equals("")){
                            ToastCustom.showToast(getApplicationContext(),"用户信息非法");
                            return;
                        }
                        userMsg.setUserId(userId);

                        add_progressBar.setVisibility(View.VISIBLE);
                        searchAndAddFriend sf = new searchAndAddFriend();
                        sf.setUserId(userId);
//                        sf.addFriendOrJoinCircle(handle, getApplicationContext());
                        sf.addFriendRequest(handle, getApplicationContext());

                    }catch (Exception e){
                        LogToSd.error("从二维码获取的用户信息失败");
                        LogToSd.error(e.getMessage());
                        Log.e("================从二维码获取的用户信息失败============",e.getMessage());
                        ToastCustom.showToast(getApplicationContext(), "获取用户信息失败");
                    }
                }


            }
        }


    }

    /* 查找好友 */
    public void searchFriend(){
        do{
            if(!searchFriendCheck())
                break;

            add_progressBar.setVisibility(View.VISIBLE);
            searchAndAddFriend sf = new searchAndAddFriend(user_account.getText().toString());
            sf.searchUser(handle,getApplicationContext());
        }while (false);
    }


    /* 发情请求好友的请求  */
    public void addFriendRequest(){
        do{
            if(!addFriendReqCheck())
                break;

            Log.e("====发起请求====","153");
            add_progressBar.setVisibility(View.VISIBLE);

            searchAndAddFriend sf = new searchAndAddFriend();
            sf.setUserId(userMsg.getUserId());
            sf.addFriendRequest(handle, getApplicationContext());

        }while (false);

    }



    private void initActivity(){
        user_account = (EditText)findViewById(R.id.user_account);
        user_head = (CircularImageView)findViewById(R.id.user_head);
        user_add = (Button)findViewById(R.id.user_add);
        user_name = (TextView)findViewById(R.id.user_name);
        user_sign = (TextView)findViewById(R.id.user_sign);
        userMsgLayout = (RelativeLayout)findViewById(R.id.user_msg);
        user_role = (TextView)findViewById(R.id.user_role);
        add_progressBar = (ProgressBar)findViewById(R.id.add_progressBar);
        add_friend_back = (ImageView)findViewById(R.id.add_friend_back);
        scan_friend_from_qr = (TextView)findViewById(R.id.scan_friend_from_qr);
        search = (TextView)findViewById(R.id.social_serarch);

        add_progressBar.setVisibility(View.GONE);
        userMsgLayout.setVisibility(View.GONE);

        intent = new Intent();
        setResult(0,intent);
    }

    public void acFinish(){
        this.finish();
    }

    class searchAndFriendHandle extends Handler {
        @Override
        public void dispatchMessage(Message msg) {

            //查找用户成功
            if(msg.what==commonData.SEARCH_FRIEND_SUCCESS_CODE){


                userMsg = (getFriendListPojo)msg.obj;
                add_progressBar.setVisibility(View.GONE);

                showUserMsg();
                return;

            }

            //发起请求成功
            if(msg.what ==commonData.ADD_FRIEND_REQUEST_SUCCESS_CODE){
                add_progressBar.setVisibility(View.GONE);
                ToastCustom.showToast(getApplicationContext(),"发送请求成功，请等待对方的回应");
                acFinish();
                return;
            }

            //发起请求失败
            if(msg.what ==commonData.ADD_FRIEND_REQUEST_FAILED_CODE){
                add_progressBar.setVisibility(View.GONE);
                ToastCustom.showToast(getApplicationContext(),"---- 发送请求失败 ----");
                return;
            }


            //用户未登录
            if(msg.what == commonData.USE_NOT_LOGIN_CODE){

                //帮组用户登录
                int flag = msg.arg1;
                if (User.getInstance() != null&&!User.getInstance().getId().equals("未填写") ) {
                    HttpUtil.apiLogin(getApplicationContext(), new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), handle,flag);

                } else if (User.getUserInfo(getApplicationContext())&&!User.getInstance().getId().equals("未填写")) {
                    HttpUtil.apiLogin(getApplicationContext(), new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), handle,flag);
                } else {
                    ToastCustom.showToast(getApplicationContext(), "请登录！");
                }

                add_progressBar.setVisibility(View.GONE);
                return;

            }

            //登录成功后
            if(msg.what == HttpUtil.LOGIN_SUCCESS){
                switch (msg.arg1){
                    case commonData.SEARCH_WITHOUT_LOGIN:
                        searchFriend();
                        break;
                    case commonData.ADD_FRIEND_REQUEST_WITHOUT_LOGIN:
                        addFriendRequest();
                        break;
                }
            }


            //需要显示提示
            if(msg.what==commonData.SHOW_TIP_CODE){
                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
                add_progressBar.setVisibility(View.GONE);
                return;
            }



            //无法连接服务器
            if (msg.what == commonData.CAN_NOT_CONNECT_SERVER_CODE){
                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
                add_progressBar.setVisibility(View.GONE);
                return;
            }

            //数据异常
            if(msg.what ==commonData.DATA_ERROR_CODE){
                add_progressBar.setVisibility(View.GONE);
                return;
            }


            //其他情况
            if(msg.what ==commonData.USER_ADD_FRIEND_OR_CIRCLE_OTHER_ERROR_CODE){
                add_progressBar.setVisibility(View.GONE);
                return;
            }

        }
    }


    /*
    * 校验
     */
    private  boolean searchFriendCheck(){
        if(user_account.getText().toString().length()>20){
            ToastCustom.showToast(getApplicationContext(), "账号过长");
            return false;
        }
        if(user_account.getText().toString().length()<=0){
            ToastCustom.showToast(getApplicationContext(), "账号为空");
            return false;
        }
        return true;
    }

    private boolean  addFriendCheck(){
        return true;
    }

    private boolean addCircleCheck(){
        return true;
    }

    private boolean addFriendReqCheck(){

        if(User.getInstance()==null){
            User.getUserInfo(getApplicationContext());
        }

        //添加自己为好友
        if(userMsg.getUserId().equals(User.getInstance().getId())){
            ToastCustom.showToast(getApplicationContext(), "您不能添加自己为好友");
            return false;
        }

        return true;
    }



    public void showUserMsg(){
        String showName = userMsg.getUserAccount();
        String reName =userMsg.getReName();
        String nickName = userMsg.getName();
        if(nickName!=null&&!nickName.equals("")){
            showName = nickName;
        }else if(reName!=null&&!reName.equals("")){
            showName =reName;
        }

        user_name.setText(showName);
        user_sign.setText(userMsg.getSign());
        user_role.setText("("+userMsg.getRole()+")");




        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderApi.getImageLoaderConfig(getApplicationContext()));

        DisplayImageOptions options =ImageLoaderApi.getOptions();
        imageLoader.displayImage(Common.baseUrl+userMsg.getHeadImg(),user_head,options);
        userMsgLayout.setVisibility(View.VISIBLE);

    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

//            setResult(1,intent);
            SocialAddActivity.this.finish();
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }







//    //登录成功后
//    if(msg.what == HttpUtil.LOGIN_SUCCESS){
//        switch (msg.arg1){
//            case commonData.SEARCH_WITHOUT_LOGIN:
//                searchFriend();
//                break;
//            case commonData.ADD_FRIEND_OR_CIRCLE_WITHOUT_LOGIN:
//                addFriendOrCircle();
//                break;
//
//            case commonData.ADD_CIRCLE_WITHOUT_LOGIN:
//                joinCircle();
//                break;
//            case commonData.ADD_FRIEND_WITHOUT_LOGIN:
//                addFriend();
//                break;
//        }
//    }




//    class searchAndFriendHandle extends Handler {
//        @Override
//        public void dispatchMessage(Message msg) {
//
//            //查找用户成功
//            if(msg.what==commonData.SEARCH_FRIEND_SUCCESS_CODE){
//
//
//                userMsg = (getFriendListPojo)msg.obj;
//                add_progressBar.setVisibility(View.GONE);
//
//                showUserMsg();
//                return;
//
//            }
//
//            //添加朋友成功
//            if(msg.what== commonData.ADD_FRIEND_SUCCESS_CODE){
//                commonData.FRIEND_LIST_CHANGE = true;
//                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//
//                setResult(1,intent);
//                return;
//            }
//
//            //加入社交圈成功
//            if(msg.what ==commonData.ADD_CIRCLE_SUCCESS_CODE){
//                commonData.FRIEND_LIST_CHANGE = true;
//                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//
//                setResult(1,intent);
//                return;
//            }
//
//            //邀请加入社交圈成功
//            if(msg.what ==commonData.INVITE_ADD_CIRCLE_SUCCESS_CODE){
//                commonData.FRIEND_LIST_CHANGE = true;
//                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//
//                setResult(1,intent);
//                return;
//            }
//
//
//            //用户已经存在社交圈
//            if(msg.what ==commonData.USER_CIRCLE_EXIST_CODE){
//                try{
//                    AlertDialog.Builder builder = new AlertDialog.Builder(SocialAddActivity.this);
//                    builder.setTitle("温馨提示")
//                            .setMessage("您已经存在社交圈，是否退出当前社交圈加入该理发师的社交圈？")
//                            .setPositiveButton("是，加入社交圈", new DialogInterface.OnClickListener() {
//                                public void onClick(DialogInterface dialog, int id) {
//                                    joinCircle();
//                                }
//                            })
//                            .setNegativeButton("否，直接添加好友", new DialogInterface.OnClickListener() {
//                                public void onClick(DialogInterface dialog, int id) {
//                                    addFriend();
//                                }
//                            }).show();
//                    add_progressBar.setVisibility(View.GONE);
//                }catch (Exception e){
//                    System.out.println(e.getMessage());
//                    e.getStackTrace();
//                }
//
//            }
//
//            //用户未登录
//            if(msg.what == commonData.USE_NOT_LOGIN_CODE){
//
//                //帮组用户登录
//                int flag = msg.arg1;
//                if (User.getInstance() != null&&!User.getInstance().getId().equals("未填写") ) {
//                    HttpUtil.apiLogin(getApplicationContext(), new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), handle,flag);
//
//                } else if (User.getUserInfo(getApplicationContext())&&!User.getInstance().getId().equals("未填写")) {
//                    HttpUtil.apiLogin(getApplicationContext(), new PeopleRegisterMsg(User.getInstance().getPhone(), User.getInstance().getPwd()), handle,flag);
//                } else {
//                    ToastCustom.showToast(getApplicationContext(), "请登录！");
//                }
//
//                add_progressBar.setVisibility(View.GONE);
//                return;
//
//            }
//
//            //登录成功后
//            if(msg.what == HttpUtil.LOGIN_SUCCESS){
//                switch (msg.arg1){
//                    case commonData.SEARCH_WITHOUT_LOGIN:
//                        searchFriend();
//                        break;
//                    case commonData.ADD_FRIEND_OR_CIRCLE_WITHOUT_LOGIN:
//                        addFriendOrCircle();
//                        break;
//
//                    case commonData.ADD_CIRCLE_WITHOUT_LOGIN:
//                        joinCircle();
//                        break;
//                    case commonData.ADD_FRIEND_WITHOUT_LOGIN:
//                        addFriend();
//                        break;
//                }
//            }
//
//            //需要显示提示
//            if(msg.what==commonData.SHOW_TIP_CODE){
//                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//                return;
//            }
//
//
//
//            //无法连接服务器
//            if (msg.what == commonData.CAN_NOT_CONNECT_SERVER_CODE){
//                ToastCustom.showToast(getApplicationContext(), msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//                return;
//            }
//
//            //数据异常
//            if(msg.what ==commonData.DATA_ERROR_CODE){
////                ToastCustom.showToast(getApplicationContext(),msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//                return;
//            }
//
//
//            //其他情况
//            if(msg.what ==commonData.USER_ADD_FRIEND_OR_CIRCLE_OTHER_ERROR_CODE){
////                ToastCustom.showToast(getApplicationContext(),msg.obj.toString());
//                add_progressBar.setVisibility(View.GONE);
//                return;
//            }
//
//
//
//
//        }
//    }
}
